package com.share.utils;


import com.share.user.admin.pojos.SysMenu;
import com.share.user.admin.vo.MenuItem;
import com.share.user.admin.vo.Meta;

import java.util.*;
import java.util.stream.Collectors;

public class MenuTreeBuilder {

    /**
     * 构建菜单树
     * @param menus 从数据库查询的菜单列表
     * @return 符合前端要求的菜单树结构
     */
    public static List<MenuItem> buildMenuTree(List<SysMenu> menus) {
        // 过滤掉隐藏的菜单并按排序号排序
        List<SysMenu> visibleMenus = menus.stream()
                .filter(menu -> menu.getVisible() == 1)
                .sorted(Comparator.comparing(SysMenu::getMenuOrder))
                .collect(Collectors.toList());

        // 构建顶级菜单
        return visibleMenus.stream()
                .filter(menu -> menu.getParentId() == 0)
                .map(menu -> convertToMenuItem(menu, visibleMenus, true))
                .collect(Collectors.toList());
    }

    /**
     * 将SysMenu转换为MenuItem
     */
    private static MenuItem convertToMenuItem(SysMenu menu, List<SysMenu> allMenus, boolean isTopLevel) {
        MenuItem item = new MenuItem();
        item.setPath(menu.getPath());

        // 优先使用name字段，如果为空则使用menuName转换
        item.setName(menu.getName() != null ? menu.getName() : convertToCamelCase(menu.getMenuName()));

        // 设置组件
        if (isTopLevel || hasChildren(menu, allMenus)) {
            item.setComponent("Layout");
        } else if (menu.getIsFrame() == 1) {
            item.setComponent("iframe/index");
        } else {
            item.setComponent(formatComponentPath(menu.getComponent()));
        }

        // 设置meta
        Meta meta = new Meta();
        meta.setTitle(menu.getMenuName());
        meta.setIcon(menu.getIcon());
        meta.setRank(menu.getMenuOrder());
        if (menu.getIsFrame() == 1) {
            meta.setFrameSrc(menu.getFrameSrc());
        }
        item.setMeta(meta);

        // 构建子菜单
        List<MenuItem> children = buildChildren(menu, allMenus);
        if (!children.isEmpty()) {
            item.setChildren(children);

            // 处理只有一个子菜单的情况
            if (children.size() == 1 && children.get(0).getChildren() == null) {
                children.get(0).setShowParent(true);
            }
        }

        return item;
    }

    /**
     * 构建子菜单列表
     */
    private static List<MenuItem> buildChildren(SysMenu parent, List<SysMenu> allMenus) {
        return allMenus.stream()
                .filter(menu -> menu.getParentId() != null && menu.getParentId().equals(parent.getId()))
                .map(menu -> convertToMenuItem(menu, allMenus, false))
                .collect(Collectors.toList());
    }

    /**
     * 检查菜单是否有子菜单
     */
    private static boolean hasChildren(SysMenu menu, List<SysMenu> allMenus) {
        return allMenus.stream().anyMatch(m -> menu.getId().equals(m.getParentId()));
    }

    /**
     * 格式化组件路径
     */
    private static String formatComponentPath(String component) {
        if (component == null) return null;
        return component.replace("@/views/", "").replace(".vue", "");
    }

    /**
     * 将菜单名称转换为驼峰式（备用，当name字段为空时使用）
     */
    private static String convertToCamelCase(String name) {
        if (name == null || name.isEmpty()) return "";
        return Arrays.stream(name.split("[^a-zA-Z0-9]"))
                .filter(word -> !word.isEmpty())
                .map(word -> word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase())
                .collect(Collectors.joining());
    }
}